--[[
-- @Author:      feilong
-- @DateTime:    2019-10-30 23:05:48
-- @Description: 日记记录
-- log文件按进程名按天生成
]]

local lfs = require "lfs"


local M = class("Handler")

function M:ctor()
    self.file = nil --文件句柄
    self.err_file = nil
    self.server_name = g.getenv("server_name") --节点名
    self.suffix = ".log" --文件后缀
    self.date = self:getDate()
    self.file_name = self.server_name.."_"..self.date --文件名
    self.path = "/home/logs/"
    self.file_maxsize = 50 *1024*1024 --文件最大M，超过会分割
    self.file_index = 0
    lfs.mkdir(self.path)

    g.loop(2000, function()
        self:checkFile()
    end)

    self:register()
end

--注册本服务里的消息
function M:register()
    --print("i am logger register!")
    g.dispatch:register("save_data", handler(self, self.saveData))
end

function M:getDate( ... )
    return os.date("%Y_%m_%d",g.time())
end

--打开一个文件， 但不关闭
function M:checkFile()
     local date = self:getDate()
     if self.date ~= date then
         self.file_index = 0
         self.date = date
         self.file_name = self.server_name.."_"..self.date --文件名
         if self.file then
             self.file:close()
             self.file = nil
         end
     end
    if self.file then
        return
    end
    local file_name = self.path .. self.file_name .. self.suffix
    self.file = io.open(file_name, "a+")
    if not self.file then
        g.log:error("log file cant open!!!!")
    end
    local file_name = self.path .. self.file_name .. "err".. self.suffix
    self.err_file = io.open(file_name, "a+")
end

--保存到文件
function M:saveData(msg, level)
    -- print("logger saveData", msg)
    if not msg and not next(msg) then
        return
    end
    self:checkFile()
    if not self.file then
        print("error: logger saveData!")
        return
    end

    local data = msg.."\n"
    self.file:write(data)
    self.file:flush()

    if level and level >= 4 then
        --对于错误文件单独放一个文件
        self:saveErrFile(data)
    end

    local file_size = self.file:seek("end")
    if file_size >= self.file_maxsize then
        --分割文件
        self.file_index = self.file_index + 1
        local file_name = self.path .. self.file_name .. self.suffix
        local rename = self.path .. self.file_name .."_"..self.file_index .. self.suffix
        self.file:close()
        self.file = nil
        os.rename(file_name, rename)
    end
end

function M:saveErrFile(data)
    if not self.err_file then
        local file_name = self.path .. self.file_name .. "err_".. self.suffix
        self.err_file = io.open(file_name, "a+")
        if  not self.err_file then
            return
        end
    end
    self.err_file:write(data)
    self.err_file:flush()
end

return M